package com.gezi.admin.security;

import com.gezi.admin.security.filter.AccessInterceptorFilter;
import com.gezi.admin.security.filter.AuthenticationHandler;
import com.gezi.admin.security.filter.JwtAuthenticationFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.access.intercept.AuthorizationFilter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Author 格子软件
 * @createDate 2024/2/10 09:00
 * @contact 公众号：格子软件 微信：13716343106 邮箱：1424529270@qq.com
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true,securedEnabled = true)
public class WebSecurityConfig {

    /**
     * 忽略路径
     */
    @Autowired
    private JwtAuthenticationFilter jwtAuthenticationFilter;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 开启跨域
        http.csrf(AbstractHttpConfigurer::disable);
        //不通过Session获取SecurityContext
        http.sessionManagement(sessionManagementConfigurer -> sessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
        //认证。这都都需要认证
        http.authorizeHttpRequests(requestMatcherConfigurer -> requestMatcherConfigurer.requestMatchers("/**").permitAll().anyRequest().authenticated());
        //token认证
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
        //认证异常处理
        http.exceptionHandling(exceptionHandlingConfigurer -> exceptionHandlingConfigurer.authenticationEntryPoint(new AuthenticationHandler()));
        //url权限认证处理
        AccessInterceptorFilter accessInterceptorFilter = new AccessInterceptorFilter(accessDecisionManager());
        http.addFilterBefore(accessInterceptorFilter, AuthorizationFilter.class);

        //视频上传
        http.headers(item->item.frameOptions(frameOptionsConfig -> frameOptionsConfig.disable()));
        return http.build();
    }

    @Bean
    public AuthorizationManager<HttpServletRequest> accessDecisionManager() {
        return new AuthenticatedAuthorizationManager();
    }
}
